<?php
namespace app\admin\controller;
use app\common\controller\AdminBase;
use app\common\model\AdminRule;
use app\common\model\AdminUsers;
use app\common\model\AdminUserGroup;

use think\Loader;

	/**
	 * 后台管理管理
	 * @author Yel   2019/6/28
	 * @copyright  yel
	 */
class AdminUser extends AdminBase{

	//+------------------------------------
	//|  管理员管理操作  start
	//+------------------------------------
	/**
	 * 用户列表
	 * @author Yel  2019/7/1
	 * @copyright  yel
	 */
	public function index(){
		//获取搜索数据
		$content = input('param.name','');
		$start = input('param.start','');
		$end = input('param.end','');
		//开辟条件空间
		$where  = [];

		if(!empty($start) && empty($end)){
			$start = strtotime($start);
			$where['addtime'] = ['egt',$start];
		}
		if(!empty($end) && empty($start)){
			$end = strtotime($end);
			$where['addtime'] = ['elt',$end];
		}
		if(!empty($end) && !empty($start)){
			$start = strtotime($start);
			$end = strtotime($end);
			$where['addtime'] = [['egt',$start],['elt',$end],'and'];
		}

		//判断数据
		if(!empty($content)){
			$where['name'] = ['like','%'.$content.'%'];
		}
		//找出全部
		//插入表
		$AdminUsers = new AdminUsers();
		$data = $AdminUsers->pageData($where,20,false,'id,name,account,email,phone,admin_user_group_id as group_name,status,addtime','addtime desc');

		// //实例化
		$UserGroup = new AdminUserGroup();
		foreach ($data['data'] as $key => $value) {
			$tempgroup = $UserGroup->findData(['id'=>$value['group_name']],'name');
			$data['data'][$key]['group_name'] = $tempgroup['name'];
		}

		$this->assign('data',$data['data']);
		$this->assign('page',$data['page']);
		return view('index');
	}


	/**
	 * 添加管理员
	 * @author Yel  2019/7/1
	 * @copyright  yel 
	 * @param string $account    账号
	 * @param int    $phone      手机号
	 * @param string $email      邮箱
	 * @param int    $group      用户组
	 * @param string $password   密码
	 * @param string $repassword 重输密码
	 */
	public function add(){
		// //实例化
		$UserGroup = new AdminUserGroup();

		// //添加管理员获取数据
		if(request()->isPost()){
			//获取数据
			$data['account']                  = input('post.account','');      //账号
			$data['email']                    = input('post.email','');        //邮箱
			$data['password']                 = input('post.password','');     //密码
			$data['repassword']               = input('post.repassword','');   //重输密码
			$data['name']                     = input('post.account','');      //用户名
			$data['phone']                    = input('post.phone','');        //手机号码
			$data['admin_user_group_id']      = input('post.group','');        //用户组ID
			$data['addtime']                  = time();                        //添加时间
			$data['status']                   = 1;                             //状态

			//数据验证
			$result = $this->validate($data,'AdminUsers.add');
			if($result !== true){
				$this->result('',-1,$result,'json');
			}
			unset($data['repassword']);
			$data['password'] = password_hash($data['password'],PASSWORD_BCRYPT);
			//插入表
			$AdminUsers = new AdminUsers();
			$op = $AdminUsers->addData($data);
			if($op){
				$this->result($op,200,'成功','json');
			}
			$this->result($op,-1,'系统错误:数据库异常','json');
		}

		//获取用户组
		$userGroup = $UserGroup->selectData([],'id,name');
		$this->assign('userGroup',$userGroup);
		return view('add');
	}

	/**
	 * 修改管理员
	 * @author Yel  2019/7/1
	 * @copyright  yel 
	 * @param int    $id         管理员ID
	 * @param string $account    账号
	 * @param int    $phone      手机号
	 * @param string $email      邮箱
	 * @param int    $group      用户组
	 * @param string $password   密码
	 * @param string $repassword 重输密码
	 */
	public function edit(){
		// //实例化
		$UserGroup = new AdminUserGroup();
		$AdminUsers = new AdminUsers();

		// 修改管理员获取数据
		if(request()->isPost()){
			//获取数据
			$id                               = input('post.ids','');          //id
			$data['email']                    = input('post.email','');        //邮箱
			$data['password']                 = input('post.password','');     //密码
			$data['repassword']               = input('post.repassword','');   //重输密码
			$data['name']                     = input('post.name','');         //用户名
			$data['phone']                    = input('post.phone','');        //手机号码
			$data['admin_user_group_id']      = input('post.group','');        //用户组ID

			//自动验证
			if(empty($id)){
				$this->result($op,-1,'参数错误：获取不到Id值','json');
			}
			if(empty($data['email'])){
				$this->result($op,-1,'邮箱不能为空','json');
			}
			$regemail = is_reg_str($data['email'],'email');
			if(!$regemail){
				$this->result($op,-1,'邮箱格式错误','json');
			}
			if($data['password']){
				$op = preg_match('/^(.+){6,12}$/',$data['password']);
				if(!$op){
					$this->result($op,-1,'密码必须6到12位','json');
				}
				if($data['password'] !== $data['repassword']){
					$this->result($op,-1,'两次密码不一致','json');
				}
				$data['password'] = password_hash($data['password'],PASSWORD_BCRYPT);
			}else{
				unset($data['password']);
			}
			unset($data['repassword']);
			if(empty($data['name'])){
				$this->result($op,-1,'用户名不能为空','json');
			}
			if(empty($data['phone'])){
				$this->result($op,-1,'电话号码','json');
			}else{
				$regphone = is_reg_str($data['phone'],'phone');
				if(!$regphone){
					$this->result($op,-1,'手机号格式错误','json');
				}
			}
			if(empty($data['admin_user_group_id'])){
				$this->result($op,-1,'请选择角色','json');
			}

			//验证唯一性
			if($AdminUsers->findData(['id'=>['neq',$id],'email'=>$data['email']],'id')){
				$this->result($op,-1,'该邮箱已经被注册','json');
			}
			if($AdminUsers->findData(['id'=>['neq',$id],'phone'=>$data['phone']],'id')){
				$this->result($op,-1,'该手机号已经被注册','json');
			}
			//插入表
			$op = $AdminUsers->saveData($data,['id'=>$id]);
			if($op){
				$this->result($op,200,'成功','json');
			}
			$this->result($op,-1,'系统错误:数据库异常','json');
		}

		//获取管理员ID
		$id = input('param.id','');
		$UserInfo = [];
		if($id){
			$UserInfo  = $AdminUsers->findData($id);
		}

		//获取用户组
		$userGroup = $UserGroup->selectData([],'id,name');

		$this->assign('userGroup',$userGroup);
		$this->assign('userInfo',$UserInfo);
		return view('edit');
	}

	/**
	 * 停用启用管理员:自动判断启动还是停用
	 * @author Yel  2019/7/3
	 * @copyright  yel
	 * @param    int  $id   管理员ID
	 */
	public function isUserStartover(){
		//获取参数
		$id = input('param.id','');
		//普通验证参数
		if(empty($id)){
			$this->result($id,-1,'参数错误:参数为null','json');
		}
		//再次验证
		//实例化
		$User = new AdminUsers();
		//获取数据
		$result  = $User -> findData(['id'=>$id],'id,status');
		if(!$result){
			$this->result($id,-1,'参数错误:找不到该数据','json');
		}
		//开辟空间
		$data = [];
		//判断是启用还是停用
		if($result['status'] == 1){ //原本是启用，下一步要执行停用
			$data['status'] = 0;
		}else{   //原本是停用，下一步要执行启用
			$data['status'] = 1;
		}
		$op = $User -> saveData($data,['id'=>$id]);
		if($op){
			$this->result($op,200,'操作成功','json');
		}
		$this->result($id,-1,'该操作失败：数据连接错误','json');
	}

	/**
	 * 删除管理员（支持批量删除）
	 * @author Yel  2019/7/3
	 * @copyright  yel
	 * @param  int|string  $id   角色ID
	 */
	public function del(){
		//获取参数
		$id = input('param.id','');
		//普通验证参数
		if(empty($id)){
			$this->result($id,-1,'参数错误:参数为null','json');
		}

		//实例化
		$User = new AdminUsers();
		//删除操作
		$op = $User -> deleteData($id);
		if($op){
			$this->result($op,200,'操作成功','json');
		}
		$this->result($id,-1,'该操作失败：数据连接错误','json');
	}
	//+------------------------------------
	//|  管理员管理操作  end
	//+------------------------------------

	//+------------------------------------
	//|  角色管理操作  start  2019/7/1 完
	//+------------------------------------
	/**
	 * 角色管理(有搜索功能)
	 * @author Yel  2019/6/28  2019/6/29 2019/7/1(搜索)
	 * @copyright  yel
	 */
	public function group_index(){
		//获取搜索数据
		$content = input('param.content','');
		// dump($content);
		//开辟条件空间
		$where  = [];
		//判断数据
		if(!empty($content)){
			$where = ['name'=>['like','%'.$content.'%']];
		}
		//实例化
		$UserGroup = new AdminUserGroup();
		//分页
		$data = $UserGroup->pageData($where,10);

		//把权限文字化
		$Rule = new AdminRule();
		foreach ($data['data'] as $k => $v) {
			$rulename = $Rule->selectData(['id'=>['in',$v['rule']]],'name');
			$data['data'][$k]['rule'] = implode('、', array_column($rulename,'name'));
		}

		$this->assign('data',$data['data']);
		$this->assign('page',$data['page']);
		return view('group_index');
	}


	/**
	 * 添加角色
	 * @author Yel  2019/6/28
	 * @copyright  yel
	 * @param  array   id   
	 * @param  string  name   
	 * @param  string  desc   
	 */
	public function group_add(){
		
		//获取post提交
		if(request()->isPost()){

			//获取参数
			$input = input('param.','');
			//检验值
			if(empty($input)){
				$this->result(false,-1,'参数异常：请刷新页面再试','json');
			}
			if(empty(trim($input['name']))){
				$this->result(false,-1,'角色名称不能为空','json');
			}
			if(empty($input['id'])){
				$this->result(false,-1,'权限规则不能为空','json');
			}
			$data['name'] = $input['name'];
			$data['desc'] = isset($input['desc'])?$input['desc']:'';
			$data['rule'] = trim(implode(',',$input['id'])); 
			//添加  返回执行条数/ID
			//实例化
			$UserGroup = new AdminUserGroup();
			$op = $UserGroup->addData($data);
			if($op){
				$this->result($data,200,'增加成功','json');
			}
			$this->result($op,-1,'增加失败','json');
		}
		//查询全部的权限
		//实例化
		$nav = new AdminRule();
		//查询所有数据
		$data = $nav->selectData([],'*','sort desc,id asc');

		//引入拓展类
		Loader::import('Org.Arraysets',EXTEND_PATH);

		//实例化
		$Arraysets = new \Arraysets;

		//按照树的形式输出
		$data = $Arraysets->getTree($data);

		//判断是否有子级
		foreach ($data as $key => $value) {
			$data[$key]['child'] = $Arraysets->haveChild($value['id'],$data,'pid');
		}
		$this->assign('data',$data);
		return view('group_add');
	}

	/**
	 * 修改角色
	 * @author Yel  2019/6/28
	 * @copyright  yel
	 * @param  int     ids   
	 * @param  array   id   
	 * @param  string  name   
	 * @param  string  desc   
	 */
	public function group_edit(){
		//实例化
		$UserGroup = new AdminUserGroup();
		
		//获取post提交
		if(request()->isPost()){

			//获取参数
			$input = input('param.','');

			//检验值
			if(empty($input)){
				$this->result(false,-1,'参数异常：请刷新页面再试','json');
			}
			if(empty($input['ids'])){
				$this->result(false,-1,'参数错误，获取不到ID','json');
			}
			if(empty(trim($input['name']))){
				$this->result(false,-1,'角色名称不能为空','json');
			}
			if(empty($input['id'])){
				$this->result(false,-1,'权限规则不能为空','json');
			}
			$data['name'] = $input['name'];
			$data['desc'] = isset($input['desc'])?$input['desc']:'';
			$data['rule'] = trim(implode(',',$input['id'])); 
			//添加  返回执行条数/ID
			
			$op = $UserGroup->saveData($data,['id'=>$input['ids']]);
			if($op){
				$this->result($data,200,'修改成功','json');
			}
			$this->result($op,-1,'修改失败','json');
		}

		//获取ID
		$id = input('param.id','');
		if(empty($id)){
			$id = 0;
		}
		//获取该角色的数据
		$group = $UserGroup -> findData(['id'=>$id]);
		
		//把权限变成数组
		if($group['rule'] != '*' &&  $group['rule'] != ''){
			$group['rule'] = explode(',',$group['rule']);
		}

		//查询全部的权限
		//实例化
		$nav = new AdminRule();
		//查询所有数据
		$data = $nav->selectData([],'*','sort desc,id asc');

		//引入拓展类
		Loader::import('Org.Arraysets',EXTEND_PATH);

		//实例化
		$Arraysets = new \Arraysets;

		//按照树的形式输出
		$data = $Arraysets->getTree($data);

		//判断是否有子级
		foreach ($data as $key => $value) {
			$data[$key]['child'] = $Arraysets->haveChild($value['id'],$data,'pid');
			$data[$key]['is_check'] = false;
			//制定已选的
			if($group['rule'] == '*'){
				$data[$key]['is_check'] = true;
			}else if(!empty($group['rule'])){
				foreach ($group['rule'] as $k => $v) {
					if($value['id'] == $v){
						$data[$key]['is_check'] = true;
					}
				}
			}
		}
		$this->assign('group',$group);
		$this->assign('data',$data);
		return view('group_edit');
	}

	/**
	 * 停用启用角色:自动判断启动还是停用
	 * @author Yel  2019/6/29
	 * @copyright  yel
	 * @param    int  $id   角色ID
	 */
	public function isStartover(){
		//获取参数
		$id = input('param.id','');
		//普通验证参数
		if(empty($id)){
			$this->result($id,-1,'参数错误:参数为null','json');
		}
		//再次验证
		//实例化
		$UserGroup = new AdminUserGroup();
		//获取数据
		$result  = $UserGroup -> findData(['id'=>$id],'id,status');
		if(!$result){
			$this->result($id,-1,'参数错误:找不到该数据','json');
		}
		//开辟空间
		$data = [];
		//判断是启用还是停用
		if($result['status'] == 1){ //原本是启用，下一步要执行停用
			$data['status'] = 0;
		}else{   //原本是停用，下一步要执行启用
			$data['status'] = 1;
		}
		$op = $UserGroup -> saveData($data,['id'=>$id]);
		if($op){
			$this->result($op,200,'操作成功','json');
		}
		$this->result($id,-1,'该操作失败：数据连接错误','json');
	}

	/**
	 * 删除角色（支持批量删除）
	 * @author Yel  2019/6/29
	 * @copyright  yel
	 * @param  int|string  $id   角色ID
	 */
	public function group_del(){
		//获取参数
		$id = input('param.id','');
		//普通验证参数
		if(empty($id)){
			$this->result($id,-1,'参数错误:参数为null','json');
		}

		//实例化
		$UserGroup = new AdminUserGroup();
		//删除操作
		$op = $UserGroup -> deleteData($id);
		if($op){
			$this->result($op,200,'操作成功','json');
		}
		$this->result($id,-1,'该操作失败：数据连接错误','json');
	}

	//+------------------------------------
	//|  角色管理操作  end
	//+------------------------------------
}	
